<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Database query builder for INSERT statements.
 *
 * @package    DBUtil
 * @author     Oliver Morgan
 */
class Kohana_Database_Query_Builder_Create extends Database_Query_Builder {
	
	/*
	 * CREATE TABLE IF NOT EXISTS `addresses` (
	 *	  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
	 *	  `house` varchar(45) NOT NULL,
	 *	  `street` varchar(45) DEFAULT NULL,
	 *	  `street_2` varchar(45) DEFAULT NULL,
	 *	  `county` varchar(45) DEFAULT NULL,
	 *	  `city` varchar(45) DEFAULT NULL,
	 *	  `post_code` varchar(7) NOT NULL,
	 *	  PRIMARY KEY (`id`)
	 *	) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; 
	 */
	
	/*
	 * $name = 'addresses';
	 * $columns = array(
	 *    'id' => array(
	 *       'int' => 10,
	 *       'unsigned',
	 *       'NOT NULL',
	 *       'AUTO_INCREMENT'
	 *    )
	 *    'house' => array(
	 *       'varchar' => 45,
	 *       'DEFAULT NULL'
	 *    )
	 *    'enum_val' => array(
	 *    	'enum' => array('val1', 'val2')
	 *    )
	 *    
	 *    etc. etc.
	 * );
	 * $options = array(
	 *    'ENGINE' => 'InnoDB',
	 *    'DEFAULT CHARSET' => 'latin1',
	 *    'AUTO_INCREMENT' => 2
	 * );
	 */
	
	protected $_columns = array();
	protected $_options = array();
	protected $_name = NULL;
		
	public function __construct($name, array $columns, array $options = NULL)
	{
		$this->_name = $name;
		$this->_columns = $columns;

		if ( ! empty($options))
		{
			$this->_options = $options;
		}

		return parent::__construct(Database::CREATE, '');
	}
	
	public function compile(Database $db)
	{
		$query = 'CREATE TABLE '.$db->quote_table($this->_name);
		
		$query .= ' (';
		
		foreach($this->_columns as $name => $options)
		{
			$query .= $db->quote_identifier($name).' ';
			
			foreach($options as $option => $param)
			{
				if(!is_int($option))
				{
					$query .= $option;
					
					if(is_array($param))
					{
						 $query .= '('.implode(',', array_walk($param, array($db, 'quote'))).')';
					}
					else
					{
						$query .= '('.$param.') ';
					}
				}
				else
				{
					$query .= $param.' ';
				}
			}
			
			$query .= ',';
		}
		
		$query .= ') ';
		
		foreach($this->_options as $option => $value)
		{
			$query .= $option.'='.$value;
		}
		
		$query .= ';';
		
		return $query;
	}
	
	public function reset()
	{
		$this->_name = NULL;

		$this->_columns =
		$this->_options = array();

		return $this;
	}
}